import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { ClassificationServiceProxy, ClassificationEditDto, ComboboxItemDto } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'createOrEditClassificationModal',
  templateUrl: './create-or-edit-classification-modal.component.html'
})
export class CreateOrEditClassificationModalComponent extends AppComponentBase {

  @ViewChild('createOrEditModal') modal: ModalDirective;
  @ViewChild('toolTypeCombobox') toolTypeCombobox: ElementRef;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;
  classification: ClassificationEditDto = new ClassificationEditDto();
  parentClassification: ClassificationEditDto = new ClassificationEditDto();

  toolTypes: ComboboxItemDto[] = [];

  constructor(
    injector: Injector,
    private _classificationService: ClassificationServiceProxy
  ) {
    super(injector);
  }

  show(id?: number, parentId?: number): void {
    this.active = true;
    this._classificationService.getClassificationForEdit(id, parentId).subscribe(result => {
      this.classification = result.classification;
      this.parentClassification = result.parentClassification;
      if (!id && this.parentClassification.displayName) {
        this.classification.displayName = this.parentClassification.displayName + '-';
      }
      if (this.parentClassification.type) {
        this.classification.type = this.parentClassification.type;
      }
      this.toolTypes = result.toolTypes;
      this.modal.show();
      // setTimeout(() => {
      //   this.toolTypeCombobox.nativeElement.selectpicker('refresh');
      // }, 0);
    });
  }

  save(): void {
    this.saving = true;

    this.classification.parentId = this.parentClassification.id;
    this._classificationService.createOrUpdateClassification(this.classification)
      .pipe(finalize(() => this.saving = false))
      .subscribe(() => {
        this.notify.info(this.l('SavedSuccessfully'));
        this.close();
        this.modalSave.emit(null);
      });
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }
}
